package com.ebrg.secure9.activity.setup;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.view.KeyEvent;

import com.ebrg.secure9.Secure9;
import com.ebrg.secure9.Preferences;
import com.ebrg.secure9.activity.Accounts;
import com.ebrg.secure9.activity.DateFormatter;
import com.ebrg.secure9.activity.K9PreferenceActivity;
import com.ebrg.secure9.service.MailService;
import com.ebrg.secure9.R;

public class Prefs extends K9PreferenceActivity
{
    private static final String PREFERENCE_THEME = "theme";
    private static final String PREFERENCE_FONT_SIZE = "font_size";
    private static final String PREFERENCE_DATE_FORMAT = "dateFormat";
    private static final String PREFERENCE_BACKGROUND_OPS = "background_ops";
    private static final String PREFERENCE_DEBUG_LOGGING = "debug_logging";
    private static final String PREFERENCE_SENSITIVE_LOGGING = "sensitive_logging";

    private static final String PREFERENCE_ANIMATIONS = "animations";
    private static final String PREFERENCE_GESTURES = "gestures";
    private static final String PREFERENCE_MANAGE_BACK = "manage_back";
    private static final String PREFERENCE_MESSAGELIST_STARS = "messagelist_stars";
    private static final String PREFERENCE_MESSAGELIST_CHECKBOXES = "messagelist_checkboxes";
    private static final String PREFERENCE_MESSAGELIST_TOUCHABLE = "messagelist_touchable";

    private static final String PREFERENCE_MESSAGEVIEW_FIXEDWIDTH = "messageview_fixedwidth_font";
    private static final String PREFERENCE_MESSAGEVIEW_RETURN_TO_LIST = "messageview_return_to_list";

    private static final String PREFERENCE_MEASURE_ACCOUNTS = "measure_accounts";
    private static final String PREFERENCE_COUNT_SEARCH = "count_search";
    private static final String PREFERENCE_GALLERY_BUG_WORKAROUND = "use_gallery_bug_workaround";
    private ListPreference mTheme;
    private ListPreference mDateFormat;
    private ListPreference mBackgroundOps;
    private CheckBoxPreference mDebugLogging;
    private CheckBoxPreference mSensitiveLogging;
    private CheckBoxPreference mGestures;
    private CheckBoxPreference mManageBack;
    private CheckBoxPreference mAnimations;
    private CheckBoxPreference mStars;
    private CheckBoxPreference mCheckboxes;
    private CheckBoxPreference mTouchable;

    private CheckBoxPreference mFixedWidth;
    private CheckBoxPreference mReturnToList;

    private CheckBoxPreference mMeasureAccounts;
    private CheckBoxPreference mCountSearch;
    private CheckBoxPreference mUseGalleryBugWorkaround;  
    private String initBackgroundOps;
    
    
    /*
    //Secure9
    private Account mAccount;
    private static final String EXTRA_ACCOUNT = "account";
    public static int whichPref;
    private CheckBoxPreference mEncryptAll;
    private CheckBoxPreference mEncryptSubject;
    private CheckBoxPreference mDefaultToKey;
    private ListPreference mAskForPin;
    */


   public static void actionPrefs(Context context)
    {
  //  	whichPref = R.xml.global_preferences;
        Intent i = new Intent(context, Prefs.class);
        context.startActivity(i);
    }
   /*
    public static void encryptionSettings(Context context, Account account)
    {

    	whichPref = R.xml.encryption_preferences;
        Intent i = new Intent(context, Prefs.class);
        i.putExtra(EXTRA_ACCOUNT, account.getUuicd());
        context.startActivity(i);
    }
*/
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.global_preferences);
       // addPreferencesFromResource(whichPref);
       // if(whichPref == R.xml.global_preferences)
      //  {
        mTheme = (ListPreference) findPreference(PREFERENCE_THEME);
        mTheme.setValue(String.valueOf(Secure9.getK9Theme() == android.R.style.Theme ? "dark" : "light"));
        mTheme.setSummary(mTheme.getEntry());
        mTheme.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
        {
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                final String summary = newValue.toString();
                int index = mTheme.findIndexOfValue(summary);
                mTheme.setSummary(mTheme.getEntries()[index]);
                mTheme.setValue(summary);
                return false;
            }
        });

        findPreference(PREFERENCE_FONT_SIZE).setOnPreferenceClickListener(
            new Preference.OnPreferenceClickListener()
        {
            public boolean onPreferenceClick(Preference preference)
            {
                onFontSizeSettings();
                return true;
            }
        });

        mDateFormat = (ListPreference) findPreference(PREFERENCE_DATE_FORMAT);
        String[] formats = DateFormatter.getFormats(this);
        CharSequence[] entries = new CharSequence[formats.length];
        CharSequence[] values = new CharSequence[formats.length];
        for (int i = 0 ; i < formats.length; i++)
        {
            String format = formats[i];
            entries[i] = DateFormatter.getSampleDate(this, format);;
            values[i] = format;
        }
        mDateFormat.setEntries(entries);
        mDateFormat.setEntryValues(values);

        mDateFormat.setValue(DateFormatter.getFormat(this));
        mDateFormat.setSummary(mDateFormat.getEntry());
        mDateFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
        {
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                final String summary = newValue.toString();
                int index = mDateFormat.findIndexOfValue(summary);
                mDateFormat.setSummary(mDateFormat.getEntries()[index]);
                mDateFormat.setValue(summary);
                return false;
            }
        });

        mBackgroundOps = (ListPreference) findPreference(PREFERENCE_BACKGROUND_OPS);
        initBackgroundOps = Secure9.getBackgroundOps().toString();
        mBackgroundOps.setValue(initBackgroundOps);
        mBackgroundOps.setSummary(mBackgroundOps.getEntry());
        mBackgroundOps.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
        {
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                final String summary = newValue.toString();
                int index = mBackgroundOps.findIndexOfValue(summary);
                mBackgroundOps.setSummary(mBackgroundOps.getEntries()[index]);
                mBackgroundOps.setValue(summary);
                return false;
            }
        });

        mDebugLogging = (CheckBoxPreference)findPreference(PREFERENCE_DEBUG_LOGGING);
        mSensitiveLogging = (CheckBoxPreference)findPreference(PREFERENCE_SENSITIVE_LOGGING);

        mDebugLogging.setChecked(Secure9.DEBUG);
        mSensitiveLogging.setChecked(Secure9.DEBUG_SENSITIVE);

        mAnimations = (CheckBoxPreference)findPreference(PREFERENCE_ANIMATIONS);
        mAnimations.setChecked(Secure9.isAnimations());
        mGestures = (CheckBoxPreference)findPreference(PREFERENCE_GESTURES);
        mGestures.setChecked(Secure9.gesturesEnabled());

        mManageBack = (CheckBoxPreference)findPreference(PREFERENCE_MANAGE_BACK);
        mManageBack.setChecked(Secure9.manageBack());


        mStars = (CheckBoxPreference)findPreference(PREFERENCE_MESSAGELIST_STARS);
        mStars.setChecked(Secure9.messageListStars());

        mCheckboxes = (CheckBoxPreference)findPreference(PREFERENCE_MESSAGELIST_CHECKBOXES);
        mCheckboxes.setChecked(Secure9.messageListCheckboxes());

        mTouchable = (CheckBoxPreference)findPreference(PREFERENCE_MESSAGELIST_TOUCHABLE);
        mTouchable.setChecked(Secure9.messageListTouchable());

        mFixedWidth = (CheckBoxPreference)findPreference(PREFERENCE_MESSAGEVIEW_FIXEDWIDTH);
        mFixedWidth.setChecked(Secure9.messageViewFixedWidthFont());

        mReturnToList = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGEVIEW_RETURN_TO_LIST);
        mReturnToList.setChecked(Secure9.messageViewReturnToList());

        mMeasureAccounts = (CheckBoxPreference)findPreference(PREFERENCE_MEASURE_ACCOUNTS);
        mMeasureAccounts.setChecked(Secure9.measureAccounts());

        mCountSearch = (CheckBoxPreference)findPreference(PREFERENCE_COUNT_SEARCH);
        mCountSearch.setChecked(Secure9.countSearchMessages());

        mUseGalleryBugWorkaround = (CheckBoxPreference)findPreference(PREFERENCE_GALLERY_BUG_WORKAROUND);
        mUseGalleryBugWorkaround.setChecked(Secure9.useGalleryBugWorkaround());
    /*    }
        else if(whichPref == R.xml.encryption_preferences){

        	//Set up account
            String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
            mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
            
           mEncryptAll = (CheckBoxPreference)findPreference("encrypt_all"); 
           mEncryptAll.setChecked(mAccount.getEncryptAll()); 

            
            mEncryptSubject = (CheckBoxPreference)findPreference("encrypt_subject");
            mEncryptSubject.setChecked(mAccount.getEncryptSubject());
    
            mDefaultToKey = (CheckBoxPreference)findPreference("use_key_by_default");
            mDefaultToKey.setChecked(mAccount.getUseKeyDefault());
            

            
            mAskForPin = (ListPreference)findPreference("ask_for_pin");
            mAskForPin.setValue(String.valueOf(mAccount.getAskForPin()));
        }*/
        
       }

    @Override
    public void onResume()
    {
        super.onResume();
    }

    private void saveSettings()
    {
   // 	if(whichPref == R.xml.global_preferences){
        SharedPreferences preferences = Preferences.getPreferences(this).getPreferences();
        Secure9.setK9Theme(mTheme.getValue().equals("dark") ? android.R.style.Theme : android.R.style.Theme_Light);
        Secure9.DEBUG = mDebugLogging.isChecked();
        Secure9.DEBUG_SENSITIVE = mSensitiveLogging.isChecked();
        boolean needsRefresh = Secure9.setBackgroundOps(mBackgroundOps.getValue());

        Secure9.setAnimations(mAnimations.isChecked());
        Secure9.setGesturesEnabled(mGestures.isChecked());
        Secure9.setManageBack(mManageBack.isChecked());
        Secure9.setMessageListStars(mStars.isChecked());
        Secure9.setMessageListCheckboxes(mCheckboxes.isChecked());
        Secure9.setMessageListTouchable(mTouchable.isChecked());

        Secure9.setMessageViewFixedWidthFont(mFixedWidth.isChecked());
        Secure9.setMessageViewReturnToList(mReturnToList.isChecked());

        Secure9.setMeasureAccounts(mMeasureAccounts.isChecked());
        Secure9.setCountSearchMessages(mCountSearch.isChecked());

        Secure9.setUseGalleryBugWorkaround(mUseGalleryBugWorkaround.isChecked());

        Editor editor = preferences.edit();
        Secure9.save(editor);
        DateFormatter.setDateFormat(editor, mDateFormat.getValue());
        editor.commit();
        if (needsRefresh)
        {
            MailService.actionReset(this, null);
        }
      //  }
    /*	else if(whichPref == R.xml.encryption_preferences)
    	{

    		
    		mAccount.setUseKeyDefault(mDefaultToKey.isChecked());
    		mAccount.setEncryptSubject(mEncryptSubject.isChecked());
    		mAccount.setEncryptAll(mEncryptAll.isChecked());
    		mAccount.setAskForPin(mAskForPin.getValue());
    		mAccount.save(Preferences.getPreferences(this));

    	}
   */
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            saveSettings();
            if (Secure9.manageBack())
            {
                Accounts.listAccounts(this);
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onFontSizeSettings()
    {
        FontSizeSettings.actionEditSettings(this);
    }

}
